package com.webserver.template_core;

import java.util.*;

public class DataSource {
    //右侧最新文章数
    private static final int TOP_15 = 15;
    //首页最新文章预览数
    private static final int INDEX_PAGE_TOP_5 = 5;
    //所有栏目及对应的文章对象
    private Map<String, List<Article>>dataSource;
    //储存所有的最新文章内容
    private List<Article>topArticles = new ArrayList<>();
    //储存前5的最新文章内容
    private List<Article>indexPageTopArticle = new ArrayList<>();
    //储存所有文章的栏目名和目录名
    private List<Map<String,String>>allSubjectName = new ArrayList<>();

    public DataSource(Map<String,List<Article>> dataSource){
        this.dataSource = dataSource;
        initTop15Article();
        initIndexPageTopArticle();
        initAllSubjectName();
    }

    private void initTop15Article(){
        Collection<List<Article>>values = dataSource.values();
        for (List<Article>e:values){
            topArticles.addAll(e);
        }
        //根据文章最后修改的时间对文章进行排序
        topArticles.sort((a1,a2)->a1.getLastModified()>a2.getLastModified()?-1:1);

        //截取前15的文章
        topArticles = topArticles.subList(0,topArticles.size()>=TOP_15?TOP_15:topArticles.size());
    }

    private void initIndexPageTopArticle(){
        indexPageTopArticle = topArticles.subList(0,topArticles.size()>=INDEX_PAGE_TOP_5?
                                    INDEX_PAGE_TOP_5:topArticles.size());
    }

    private void initAllSubjectName(){
        for (String key:dataSource.keySet()){
            String[]keydata = key.split("_");
            Map<String,String>map = new HashMap<>();
            map.put("pathName",keydata[0]);
            map.put("subjectName",keydata[1]);
            allSubjectName.add(map);
        }
    }

    public Map<String, List<Article>> getDataSource() {
        return dataSource;
    }

    public void setDataSource(Map<String, List<Article>> dataSource) {
        this.dataSource = dataSource;
    }

    public List<Article> getTopArticles() {
        return topArticles;
    }

    public void setTopArticles(List<Article> topArticles) {
        this.topArticles = topArticles;
    }

    public List<Article> getIndexPageTopArticle() {
        return indexPageTopArticle;
    }

    public void setIndexPageTopArticle(List<Article> indexPageTopArticle) {
        this.indexPageTopArticle = indexPageTopArticle;
    }

    public List<Map<String, String>> getAllSubjectName() {
        return allSubjectName;
    }

    public void setAllSubjectName(List<Map<String, String>> allSubjectName) {
        this.allSubjectName = allSubjectName;
    }
}
